#!/usr/bin/env node
const http=require('http'),
      qs=require('querystring'),
      url=require('url'),
      fs=require('fs');
let items=[];
function genPage(){
  let html=fs.readFileSync('./template.html').toString('utf8');
  html=html.replace('%',items.map(i=>'<li>'+i+'</li>').join('\n'));
  return html;
}
http.createServer((req,res)=>{
  let addr=url.parse(req.url);
 
  if(addr.pathname!=='/'){
    res.statusCode=404;
    res.setHeader('conten-type','text/html');
    res.end('<h1>Not Found</h1>');
    return;
  }
  let data='';
  req.on('data',chunk=> data += chunk);
  req.on('end',()=>{
    console.log(qs.parse(data));
    let item=qs.parse(data).item;
    console.log(item);
    if(item!=='' && typeof item!=='undefined'){
      items.push(item);
    }
    res.writeHead(200,{
      'content-type':'text/html',
      'content-length':Buffer.byteLength(genPage())
    });
    res.end(genPage());
  });
  
}).listen(8080);

